import React, { useEffect } from 'react';
import { Anchor, Form, Checkbox, Button, Result, Typography, message, Divider, ConfigProvider } from 'antd';
import moment from 'moment';
import { connect } from 'umi';
import request from '@/utils/request';
import { getOrganization } from '@/utils/utils';
// import useParseResume from '@/hooks/useParseResume';
import Form1 from './components/Form1';
import Form2 from './components/Form2';
import Form3 from './components/Form3';
import Form4 from './components/Form4';
import Form5 from './components/Form5';
import Form6 from './components/Form6';
import Form7 from './components/Form7';
import styles from './index.less';

const { Paragraph } = Typography;

const ApplicationForm = props => {
    const {
        dictionary,
        form,
        location,
        dispatch,
        form: { getFieldDecorator }
    } = props;
    const {
        query: { talentCode, key: talentKey }
    } = location;
    const paragraphText =
        '应聘登记表中所提供的信息是全面且准确的；公司可对表中有关的信息进行调查,公司亦有权查阅本人各种材料以及向第三方做个人访谈（如应聘者原雇主、家庭成员、业务联系人、经济来源人、朋友等）。由于本人提供虚假信息的，公司方面有权在核实后随时终止劳动合同。';
    const declaration = '本人已阅读上述申明';
    const [welcomeCompany, setWelcomeCompany] = React.useState('');
    const [isAgreeFrom, setIsAgreeFrom] = React.useState(false);
    const [isPageEffective, setIsPageEffective] = React.useState(true);
    const [isFinish, setIsFinish] = React.useState(false);
    const [talentInfo, setTalentInfo] = React.useState({});
    const [loading, setLoading] = React.useState(false);
    const renderAnchor = () => {
        const { Link } = Anchor;
        return (
            <Anchor
                getContainer={() => document.getElementById('scrollContainer') || window}
                offsetTop={24}
                bounds={64}
            >
                <Link href="#form1" title="个人信息" />
                <Link href="#form2" title="紧急联系人" />
                <Link href="#form3" title="应聘信息" />
                <Link href="#form4" title="工作经历" />
                <Link href="#form5" title="教育经历" />
                <Link href="#form6" title="培训经历" />
                <Link href="#form7" title="获奖记录" />
            </Anchor>
        );
    };
    // 表单提交
    const handleSubmit = e => {
        e.preventDefault();
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const result = { talentCode };
                const originData = values;
                Object.keys(originData).forEach(key => {
                    const arr = key.split('_');
                    if (originData[key] || originData[key] === 0) {
                        if (arr[2]) {
                            if (!result[arr[0]]) {
                                result[arr[0]] = [];
                            }
                            if (!result[arr[0]][Number(arr[2])]) {
                                result[arr[0]][Number(arr[2])] = {};
                            }
                            if (originData[key] || originData[key] === 0) {
                                if (arr[1] === 'dateRange') {
                                    if (originData[key][0]) {
                                        result[arr[0]][Number(arr[2])].startTime = moment(originData[key][0]).format(
                                            'YYYY-MM-01'
                                        ); // 必须加上是几日,否则接口会报参数无效
                                        result[arr[0]][Number(arr[2])].endTime = moment(originData[key][1]).format(
                                            'YYYY-MM-01'
                                        );
                                    }
                                } else if (originData[key] instanceof moment) {
                                    result[arr[0]][Number(arr[2])][arr[1]] = moment(originData[key]).format(
                                        'YYYY-MM-01'
                                    );
                                } else {
                                    result[arr[0]][Number(arr[2])][arr[1]] = originData[key];
                                }
                            }
                        } else if (typeof originData[key] === 'boolean') {
                            result[arr[0]] = originData[key] ? 1 : 0;
                        } else if (originData[key] instanceof moment) {
                            result[arr[0]] = moment(originData[key]).format('YYYY-MM-DD');
                        } else {
                            result[arr[0]] = originData[key];
                        }
                    }
                });
                const haveObjInArr = arrData => {
                    let ret = false;
                    for (let i = 0; i < arrData.length; i += 1) {
                        if (typeof arrData[i] === 'object') {
                            ret = true;
                            break;
                        }
                    }
                    return ret;
                };
                Object.keys(result).forEach(rKey => {
                    if (Array.isArray(result[rKey]) && haveObjInArr(result[rKey])) {
                        const newArr = [];
                        result[rKey].forEach(item => {
                            if (item && Object.keys(item).length > 0) {
                                const { id, deleteFlag, ...otherField } = item;
                                const validField = Object.keys(otherField).find(field => {
                                    if (field) {
                                        return true;
                                    }
                                    return false;
                                });
                                newArr.push({ ...item, deleteFlag: validField ? 0 : 1 });
                            }
                        });
                        result[rKey] = newArr;
                    }
                });
                setLoading(true);
                const response = await request('/api/oa/v1/registration/addRegistration', {
                    method: 'post',
                    data: result
                });
                setLoading(false);
                if (response.code === 10000) {
                    setIsFinish(true);
                } else {
                    message.error(response.msg || '提交失败！');
                }
            }
        });
    };
    const renderRecruitForm = () => {
        const subFormProps = { form, dict: dictionary, initialFormInfo: talentInfo };
        const formItemLayout = {
            labelCol: {
                md: { span: 8 },
                xs: { span: 24 },
                sm: { span: 24 }
            },
            wrapperCol: {
                md: { span: 16 },
                xs: { span: 24 },
                sm: { span: 24 }
            }
        };
        return (
            <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
                <Form {...formItemLayout} onSubmit={handleSubmit}>
                    <Form1 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Form2 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Form3 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Form4 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Form5 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Form6 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Form7 {...subFormProps} />
                    <Divider className={styles.divider} />
                    <Paragraph strong style={{ marginTop: 32 }}>
                        本人在此申明：
                    </Paragraph>
                    <Paragraph>{paragraphText}</Paragraph>
                    <Form.Item vvspan={24} labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
                        {getFieldDecorator('acceptedDate', {
                            initialValue: moment().format('YYYY-MM-DD')
                        })(<div className={styles.applyDate}>应聘日期：{moment().format('YYYY年MM月DD号')}</div>)}
                    </Form.Item>
                    <Form.Item vvspan={24} labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
                        {getFieldDecorator('agreeForm', {
                            initialValue: isAgreeFrom
                        })(
                            <Checkbox
                                onChange={e => {
                                    setIsAgreeFrom(e.target.checked);
                                }}
                                style={{ lineHeight: '20px' }}
                            >
                                {declaration}
                            </Checkbox>
                        )}
                    </Form.Item>
                    <div></div>
                    <div className={styles.btnItem}>
                        <Button type="primary" htmlType="submit" disabled={!isAgreeFrom} loading={loading}>
                            提交
                        </Button>
                    </div>
                </Form>
            </ConfigProvider>
        );
    };
    const getDict = React.useCallback(() => {
        dispatch({
            type: 'dictionary/fetchDictionaryList',
            payload: {
                codes: [
                    'agreeType',
                    'sexType',
                    'healthyState',
                    'emergencyRelationship',
                    'household',
                    'liveTogether',
                    'backCheckAccepted',
                    'SingaporeRecruitWay',
                    'academicYear',
                    'industryType',
                    'ChinaRecruitWay'
                ]
            }
        });
    }, [talentCode]);
    const checkEffect = async () => {
        let result = true;
        const response = await request('/api/oa/v1/registration/checkValidity', {
            method: 'post',
            data: {
                talentCode,
                key: talentKey
            }
        });
        if (response.code !== 10000) {
            result = false;
            setIsPageEffective(false);
        }
        return result;
    };
    const getTalentInfo = React.useCallback(async () => {
        const response = await request('/api/oa/v1/registration/getRegistrationInfo', {
            method: 'post',
            data: { talentCode }
        });
        if (response.code === 10000) {
            setTalentInfo(response.data);
            setWelcomeCompany(getOrganization(response.data.companyId).name);
        }
    }, [talentCode]);

    useEffect(() => {
        if (checkEffect()) {
            getDict();
            getTalentInfo();
        }
    }, []);
    const renderInEffectivePage = <Result status="error" title="当前链接已失效！"></Result>;
    const renderSuccessPage = <Result status="success" title="提交成功！"></Result>;
    const renderFormPage = isFinish ? (
        renderSuccessPage
    ) : (
        <div className={styles.page_wrap} id="scrollContainer">
            <div className={styles.top_img}>{`欢迎应聘${welcomeCompany}，请先完善您的简历信息`}</div>
            <div className={styles.page}>
                <div className={styles.form_wrap}>{renderRecruitForm()}</div>
                <div className={styles.anchor_wrap}>{renderAnchor()}</div>
            </div>
        </div>
    );

    return isPageEffective ? renderFormPage : renderInEffectivePage;
};

export default connect(({ dictionary }) => ({
    dictionary
}))(Form.create()(React.memo(ApplicationForm)));
